const app = document.createElement('div')
const app_base_url = window.app_base_url
document.getElementById('v-container').appendChild(app)
app.id = 'app'
app.className = 'apps'
new Vue({
    el: '#app',
    template:
        //  <div>
        //     <div class="d-flex align-items-center ps-2">
        //       <el-select v-model="currentDevice" placeholder="请选择" size="small" @change="selectChange">
        //         <el-option
        //           v-for="item in deviceList"
        //           :key="item.value"
        //           :label="item.label"
        //           :value="item.value">
        //         </el-option>
        //       </el-select>
        //       <el-button type="primary" size="small" @click="openDrawer()" class="ms-2" v-if="loginStatus">操作</el-button>
        //       <el-popover
        //         v-if="loginStatus"
        //         placement="bottom"
        //         class="ms-sm-2"
        //         width="200"
        //         ref="myPopover1"
        //         trigger="click">
        //         <el-form :model="ruleForm3" ref="ruleForm3" size="small" class="p-3" label-width="auto" :inline="true">
        //             <el-form-item label="GPS频率" prop="updatefreq" :rules="[{ required: true, message: '频率不能为空'}]" style="width: 150px">
        //                 <el-input-number class="w-100" controls-position="right" v-model="ruleForm3.updatefreq"></el-input-number>
        //             </el-form-item>
        //             <el-form-item class="w-100 d-flex justify-content-center">
        //                 <el-button type="primary" @click="submitForm3()">发送</el-button>
        //             </el-form-item>
        //         </el-form>
        //         <div slot="reference">
        //             <el-button size="small" type="danger" class="d-none d-sm-block" plain>设置频率</el-button>
        //             <el-button size="small" type="danger" icon="el-icon-setting" circle class="d-sm-none d-block"></el-button>
        //         </div>
        //       </el-popover>
        //       <el-badge :value="devicee.deviceMsg.length" :max="99" class="mx-sm-2">
        //         <el-button size="small" @click="drawerVisible3=true" type="warning" class="d-none d-sm-block">数据日志</el-button>
        //         <el-button size="small" @click="drawerVisible3=true" type="warning" icon="el-icon-message" circle class="d-sm-none d-block"></el-button>
        //       </el-badge>
        //       <div v-if="!loginStatus">
        //         <el-button size="small" @click="handleLogin" type="info" class="d-none d-sm-block">登录</el-button>
        //         <el-button size="small" @click="handleLogin" type="info" icon="el-icon-s-custom" circle class="d-sm-none d-block"></el-button>
        //       </div>
        //       <el-dropdown @command="handleCommand" class="ms-2 ms-sm-0" v-else>
        //         <img style="width: 32px;" src="./images/icon_administrator.png" />
        //         <el-dropdown-menu slot="dropdown">
        //             <el-dropdown-item command="a">退出登录</el-dropdown-item>
        //         </el-dropdown-menu>
        //       </el-dropdown>
        //     </div>
        `
    <div>
        <el-collapse accordion v-model="activeCollapseName">
            <el-collapse-item name="0">
                <div class="d-flex flex-column">
                    <div v-if="!loginStatus">
                        <el-button @click="handleLogin" style="width: 40px" type="info" icon="el-icon-s-custom" circle></el-button>
                    </div>
                    <el-dropdown @command="handleCommand" v-else>
                        <img style="width: 40px;" src="./images/icon_administrator.png" />
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item command="a">退出登录</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <div class="d-flex justify-content-center mb-3">
                        <c-battery class="mt-3" :capacity="volume" :voltage="voltage"></c-battery>
                    </div>
                    <el-popover placement="left" class="mt-3" width="300" trigger="click" v-model="datePickerVisible">
                        <el-date-picker
                            v-model="startTime"
                            type="datetime"
                            class="w-100"
                            placeholder="选择开始记录时间"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            size="small">
                        </el-date-picker>
                        <div class="mt-2 d-flex justify-content-center">
                            <el-button type="plain" size="mini" @click="closeDatePickerPopver()">重置</el-button>
                            <el-button type="primary" size="mini" @click="submitDatePickerPopver()">确定</el-button>
                        </div>
                        <div slot="reference">
                            <el-button type="primary" style="width: 40px" circle icon="el-icon-date"></el-button>
                        </div>
                    </el-popover>
                    <el-popover placement="left" class="mt-3" width="200" trigger="click">
                        <el-select v-model="currentDevice" placeholder="请选择" size="small" @change="selectChange">
                            <el-option v-for="item in deviceList" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                        <div slot="reference">
                            <el-button type="primary" style="width: 40px" circle>{{ currentDevice.at(-1) }}</el-button>
                        </div>
                    </el-popover>
                    <el-button type="primary" style="width: 40px" @click="openDrawer()" class="mt-3" icon="el-icon-thumb" v-if="loginStatus" circle></el-button>
                    <el-popover  v-if="loginStatus" placement="left" class="mt-3" width="200" ref="myPopover1" trigger="click">
                        <el-form :model="ruleForm3" ref="ruleForm3" size="small" class="p-3" label-width="150" :inline="true">
                            <el-form-item label="GPS频率" prop="updatefreq" :rules="[{ required: true, message: '频率不能为空'}]" style="width: 150px">
                                <el-input-number class="w-100" controls-position="right" v-model="ruleForm3.updatefreq"></el-input-number>
                            </el-form-item>
                            <el-form-item class="w-100 d-flex justify-content-center">
                                <el-button type="primary" @click="submitForm3()">发送</el-button>
                            </el-form-item>
                        </el-form>
                        <div slot="reference">
                            <el-button type="primary" style="width: 40px" icon="el-icon-setting" circle></el-button>
                        </div>
                    </el-popover>
                    <el-badge :value="devicee.deviceMsg.length" :max="99" class="mt-3">
                        <el-button @click="drawerVisible3=true" type="info" icon="el-icon-message" circle></el-button>
                    </el-badge>
                </div>
            </el-collapse-item>
        </el-collapse>
        <el-drawer
            :title="currentDevice"
            :visible.sync="drawerVisible"
            direction="rtl"
            :before-close="handleClose">
            <div class="d-flex justify-content-center">
                <el-form :model="ruleForm" :rules="rules" ref="ruleForm" size="small" class="p-3" label-width="100px">
                    <el-form-item label="电池电压">
                        <div style="display: flex">
                            <div>{{voltage || '--'}}mv</div>
                            <div class="ms-3">电量：{{volume || '--'}}%</div>
                        </div>
                    </el-form-item>
                    <el-form-item label="频率" prop="freq">
                        <el-input-number class="w-100" controls-position="right" v-model="ruleForm.freq"></el-input-number>
                    </el-form-item>
                    <el-form-item label="波组个数" prop="wavegroup">
                        <el-input-number class="w-100" controls-position="right" v-model="ruleForm.wavegroup"></el-input-number>
                    </el-form-item>
                    <el-form-item label="组波个数" prop="wavenumber">
                        <el-input-number class="w-100" controls-position="right" v-model="ruleForm.wavenumber"></el-input-number>
                    </el-form-item>
                    <el-form-item label="电流强度" prop="current">
                        <el-input-number class="w-100" controls-position="right" v-model="ruleForm.current"></el-input-number>
                    </el-form-item>
                    <el-form-item label="输出端口" prop="port">
                        <el-input-number class="w-100" controls-position="right" v-model="ruleForm.port"></el-input-number>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm()">发送</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>
        <el-drawer
        title="设置电子围栏"
        :visible.sync="drawerVisible2"
        direction="rtl"
        :before-close="handleClose2">
            <div class="d-flex justify-content-center">
                <el-form :model="ruleForm2" :rules="rules2" ref="ruleForm2" size="small" class="p-3" label-width="60px">
                    <el-form-item label="纬度" prop="lat">
                        <el-input type="number" class="w-100" controls-position="right" v-model="ruleForm2.lat"></el-input>
                    </el-form-item>
                    <el-form-item label="经度" prop="lng">
                        <el-input type="number" class="w-100" controls-position="right" v-model="ruleForm2.lng"></el-input>
                    </el-form-item>
                    <el-form-item label="半径" prop="radiu">
                        <el-input-number class="w-100" controls-position="right" v-model="ruleForm2.radiu"></el-input-number>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="submitForm2()">发送</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>
        <el-drawer
        title="历史消息"
        :visible.sync="drawerVisible3"
        direction="rtl">
            <div class="px-3 w-100">
                <div v-for="(item, index) in devicee.deviceMsg" :key="index" class="pb-2 border-bottom w-100">
                    <div>{{item.info0}}</div>
                    <div>{{item.info1}}</div>
                    <div>{{item.info2}}</div>
                    <div>{{item.info3}}</div>
                </div>
            </div>
        </el-drawer>
        <el-dialog
            :visible.sync="loginDialogVisible"
            class="login-dialog"
            :close-on-click-modal="false"
            width="30%">
            <div class="d-flex justify-content-center w-100 pb-5">
                <el-form :model="loginForm" style="max-width: 300px; min-width: 250px">
                    <el-form-item>
                        <div class="w-100 d-flex justify-content-center fs-5">登录</div>
                    </el-form-item>
                    <el-form-item prop="username">
                        <el-input v-model="loginForm.username" calss="w-100" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                    <el-form-item prop="password">
                        <el-input v-model="loginForm.password" type="password" placeholder="请输入密码"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" round class="w-100" @click="submitLoginForm()">登录</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-dialog>
    </div>
    `,
    data() {
        return {
            startTime: "",
            ruleForm3: {
                updatefreq: 1,
                command: 3,
            },
            datePickerVisible: false,
            devicee: {
                deviceMsg: []
            },
            drawerVisible3: false,
            loginDialogVisible: false,
            deviceList: [
                {
                    value: 'BIRDS_GNSS1',
                    label: '1号设备',
                },
                {
                    value: 'BIRDS_GNSS2',
                    label: '2号设备',
                },
                {
                    value: 'BIRDS_GNSS3',
                    label: '3号设备',
                },
                {
                    value: 'BIRDS_GNSS4',
                    label: '4号设备',
                },
                {
                    value: 'BIRDS_GNSS5',
                    label: '5号设备',
                },
            ],
            drawerVisible: false,
            currentDevice: 'BIRDS_GNSS1',
            ruleForm: {
                command: 1,
                freq: 100,
                wavegroup: 3,
                wavenumber: 5,
                current: 500,
                port: 1,
            },
            rules: {
                freq: [
                    { required: true, message: '频率不能为空', trigger: 'blur' },
                ],
                wavegroup: [
                    { required: true, message: '波组个数不能为空', trigger: 'blur' },
                ],
                wavenumber: [
                    { required: true, message: '组波个数不能为空', trigger: 'blur' },
                ],
                current: [
                    { required: true, message: '电流强度不能为空', trigger: 'blur' },
                ],
                port: [
                    { required: true, message: '输出端口不能为空', trigger: 'blur' },
                ],
            },
            timer: null,
            voltage: 0,
            volume: 0,
            // pointMarker: null,
            // pointCircle: null,
            drawerVisible2: false,
            ruleForm2: {
                command: 2,
                lng: null,
                lat: null,
                radiu: 1000,
            },
            rules2: {
                lng: [
                    { required: true, message: '经度不能为空', trigger: 'blur' },
                ],
                lat: [
                    { required: true, message: '纬度不能为空', trigger: 'blur' },
                ],
                radiu: [
                    { required: true, message: '半径不能为空', trigger: 'blur' },
                ]
            },
            loginForm: {
                username: '',
                password: ''
            },
            loginStatus: false,
            activeCollapseName: "0"
        }
    },
    created() {
        window.__this = this
    },
    mounted() {
        // 绘制电子围栏
        map.addEventListener("dblclick", this.addDzwl)
        this.loginStatus = !!localStorage.getItem('token');
        this.startTime = this.getFormattedDate()
    },
    methods: {
        submitDatePickerPopver() {
            this.datePickerVisible = false
            window.setInitPloyline(this.currentDevice, this.startTime)
        },
        closeDatePickerPopver() {
            this.startTime = this.getFormattedDate()
            window.baiduMap.clearOverlays()
            window.setInitPloyline(this.currentDevice, this.startTime)
            this.datePickerVisible = false
        },
        getFormattedDate() {
            // 创建一个Date对象
            var today = new Date();
            // 获取年、月、日
            var year = today.getFullYear();
            var month = today.getMonth() + 1; // 月份是从0开始的
            var day = today.getDate();
            // 补零函数
            function padTo2Digits(num) {
                return num.toString().padStart(2, '0');
            }
            // 返回格式化的日期
            return `${year}-${padTo2Digits(month)}-${padTo2Digits(day)} 00:00:00`;
        },
        getToken() {
            const token = localStorage.getItem('token')
            return token ? `Bearer ${token}` : '';
        },
        handleCommand() {
            this.loginStatus = false
            localStorage.removeItem('token')
            this.$message.success('已退出登录')
        },
        handleLogin() {
            this.loginDialogVisible = true
        },
        submitLoginForm() {
            const { username, password } = this.loginForm
            if (!username || !password) return this.$message.error('用户名或密码不能为空')
            axios({
                url: app_base_url + '/api/login',
                method: 'post',
                data: {
                    username,
                    password
                },
            }).then(res => {
                if (res?.data?.data?.token) {
                    localStorage.setItem('token', res.data.data.token)
                    this.loginStatus = true
                    this.$message.success('登录成功')
                    this.loginDialogVisible = false
                }
            }).catch(err => {
                console.log(err);
                const msg = err?.response?.data?.message || '系统异常'
                this.$message.error(msg)
            })
            // this.loginDialogVisible = false
        },
        addDzwl(e) {
            var point = e.latlng;
            this.drawerVisible2 = true
            this.ruleForm2.lng = point.lng
            this.ruleForm2.lat = point.lat
        },
        submitForm() {
            if (!window.lastMarker) return this.$message.error('未收到鸽子位置，无法发送指令')
            this.authApi().then(() => {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        const params = { ...this.ruleForm }
                        const latlng = window?.lastMarker?.latLng
                        const lat = latlng?.lat
                        const lng = latlng?.lng
                        params.lat = lat
                        params.lng = lng
                        window.wss.send(JSON.stringify({ "_params": params, "_topic": this.currentDevice }));
                        this.$message.success('发送刺激信号成功！')
                        this.drawerVisible = false
                    } else {
                        this.$message.error('请填写必填项！')
                        return false
                    }
                })
            })
        },
        submitForm2() {
            this.authApi().then(() => {
                this.$refs.ruleForm2.validate((valid) => {
                    if (valid) {
                        window.wss.send(JSON.stringify({ "_params": this.ruleForm2, "_topic": this.currentDevice }));
                        this.$message.success('发送创建电子围栏指令成功！')
                        this.drawerVisible2 = false
                        // if (this.pointCircle) {
                        //     map.removeOverlay(this.pointCircle);
                        //     this.pointCircle = null
                        // }
                        // this.pointCircle = new BMapGL.Circle(new BMapGL.Point(this.ruleForm2.lng, this.ruleForm2.lat), this.ruleForm2.radiu, { strokeColor: "blue", strokeWeight: 2, strokeOpacity: 0.5 });
                        // map.addOverlay(this.pointCircle);
                        // if (this.pointMarker) {
                        //     map.removeOverlay(this.pointMarker);
                        //     this.pointMarker = null
                        // }
                        // this.pointMarker = new BMapGL.Marker(new BMapGL.Point(this.ruleForm2.lng, this.ruleForm2.lat));
                        // map.addOverlay(this.pointMarker);
                    } else {
                        this.$message.error('请填写必填项！')
                        return false
                    }
                })
            })
        },
        submitForm3() {
            this.authApi().then(() => {
                this.$refs.ruleForm3.validate((valid) => {
                    if (valid) {
                        window.wss.send(JSON.stringify({ "_params": this.ruleForm3, "_topic": this.currentDevice }));
                        this.$message.success('发送设置频率信号成功！')
                        this.$nextTick(() => {
                            this.$refs.myPopover1.doClose();
                        });
                    } else {
                        this.$message.error('请填写必填项！')
                        return false
                    }
                })
            })
        },
        handleClose(done) {
            this.$refs.ruleForm.resetFields()
            // this.currentDevice = ''
            done()
        },
        handleClose2(done) {
            this.$refs.ruleForm2.resetFields()
            done()
        },
        openDrawer() {
            this.authApi().then(() => {
                this.drawerVisible = true
            })
        },
        selectChange(val) {
            window.baiduMap.clearOverlays()
            window.setInitPloyline(val, this.startTime)
            // window.wss.send(JSON.stringify({ "topic": val }));
            // 清空上个设备存储的电池数据
            window._device_info = {}
            this.voltage = 0
            this.volume = 0
        },
        authApi() {
            return new Promise((resolve, reject) => {
                axios({
                    url: app_base_url + '/log/auth',
                    method: 'post',
                    headers: {
                        'Authorization': this.getToken()
                    }
                }).then(res => {
                    resolve(res)
                }).catch(err => {
                    this.drawerVisible = false
                    this.drawerVisible2 = false
                    message = ''
                    if (err.message === 'Network Error') {
                        message = '网络错误'
                    } else if (err.message === 'Request failed with status code 403') {
                        localStorage.removeItem('token')
                        this.loginStatus = false
                        message = '账号已在其他设备登录，请重新登录'
                    } else if (err.message === 'Request failed with status code 401') {
                        localStorage.removeItem('token')
                        this.loginStatus = false
                        message = '登录验证已过期，请重新登录'
                    } else {
                        message = '未知错误'
                    }
                    this.$message.error(message)
                    reject(err)
                })
            })
        }
    },
})


Vue.component("c-battery", {
    template: `
    <div class="battery-container">
        <div class="shell">
            <div
                v-for="(item, index) in batteryChunk"
                class="block"
                :key="index"
                :style="{ background: batteryColor }"
            ></div>
        </div>
        <div class="battery-number">{{capacity}}</div>
        <div class="">{{voltage}}v</div>
    </div>
    `,
    props:{
        capacity:{
          type: [Number,String],
        },
        voltage:{
          type: [Number,String],
        }
      },
      computed:{
        batteryChunk(){
          return this.findInterval(this.capacity)
        },
        batteryColor(){
          if(this.batteryChunk >=0 && this.batteryChunk <= 1){
            return '#FE5F69'
          }else if(this.batteryChunk > 1 && this.batteryChunk <=4){
            return '#FFC95C'
          }else{
            return '#64BA8C'
          }
        }
      },
      methods:{
        findInterval(num) {
          var intervalSize = 100 / 6
          var interval = Math.floor(num / intervalSize)
          if (interval === 6) {
            return interval
          } else {
            return interval + 1
          }
        }
      }
})
